---
title: ''
output: pdf_document
classoption: landscape
fig_width: 10 
fig_height: 6 
---

```{r setup, include=FALSE, message=FALSE}

# Package setup
if (!require("pacman")) install.packages("pacman", repos = "http://cran.us.r-project.org"); library(pacman);
pacman::p_load(yaml, arrow, readr, tidyr, glue, argparse, here, purrr, stringr, 
               knitr, kableExtra, ggplot2, gridExtra, dplyr, cowplot);

# Working directory and command line argument setup
current_script = "generate_tables_and_figures/gen_time_varying_itt_outputs/src/gen_time_varying_itt_outputs.Rmd"
here::i_am(current_script)
source(here("R", "project_functions.R"))
task_dir = here(dirname(dirname(file.path(current_script))))
knitr::opts_knit$set(root.dir = task_dir)
cl_args <- parse_make_args(c(
  "RMD_FILE",
  "TIME_VARYING_ITT_STATS_FILE",
  "OUTCOME_LABELS_FILE",
  "CONFIG_FILE",
  "OUT_DIR"
), inter_active = TRUE, task_dir = task_dir)

knitr_setup()

```


```{r}

estimates <- read_csv(cl_args$TIME_VARYING_ITT_STATS_FILE, show_col_types = F)

ylabels <- read_csv(cl_args$OUTCOME_LABELS_FILE, show_col_types = F) %>%
  rename(outcome = value)

params <- read_yaml(cl_args$CONFIG_FILE)

```


```{r}

estimates <- estimates %>%
  left_join(ylabels %>% select(outcome, label), by = 'outcome') %>%
  mutate(window = as.integer(str_extract(window, '\\d+'))) %>%
  mutate(beta_itt_ci_upper = beta_itt + params$ci_band * stderr_itt,
         beta_itt_ci_lower = beta_itt - params$ci_band * stderr_itt)


```


```{r}

plot_list = list()
for (label in names(params$plot_list)) {
  
  metric = params$plot_list[[label]][['metric']]
  ylab_str = params$plot_list[[label]][['yaxis_label']]

  p <- estimates %>%
    filter(label == !!label) %>%
    ggplot(mapping = aes(window, !!sym(metric))) +
    theme_minimal() +
    theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), 
          panel.background = element_blank()) +
    theme(plot.title = element_text(hjust = 0.5)) +
    scale_x_continuous(name="Months since randomization", breaks = sort(unique(estimates$window))) +
    ylab(ylab_str) +
    ggtitle(label) +
    theme(panel.border = element_blank(), 
          axis.line = element_line(color = "black", linewidth = .3, linetype = "solid"),
          axis.ticks = element_line(color = 'black'), 
          axis.text.x = element_text(size = params$axis_size),
          axis.title.x = element_text(size = params$axis_label_size),
          axis.text.y = element_text(size = params$axis_size),
          axis.title.y = element_text(size = params$axis_label_size),
          legend.text = element_text(size = params$axis_size),
          title = element_text(size = params$title_size),
          text=element_text(family="Times"))
  
  if (label != 'Participation') {
    p <- p +
      geom_point(shape='square', size=2.75) +
      geom_hline(yintercept = 0, size=.5) +
      geom_errorbar(aes(ymin=beta_itt_ci_lower, ymax=beta_itt_ci_upper), 
                  width=.8, color='#939797')
  } else {
    p <- p +
      geom_point(shape='diamond', size=3.25, color='grey') +
      geom_line(color='grey') +
      ylim(0, .6)
  }

  plot_list[[length(plot_list)+1]] = p
  
}

# fake empty plot
ci_text = '95% confidence interval'
empty_plot <- tibble(x=c(1), y=c(1), ci=c(.05)) %>%
  ggplot(aes(x=x, y=y)) +
  geom_point(size=5) +
  geom_errorbar(aes(x=x, ymin=y-ci, ymax=y+ci, width=.1, col=ci_text)) +
  scale_color_manual(name = "", limits = c(ci_text), values = c( "black")) + 
  guides(colour = guide_legend(override.aes = list(linetype = c("solid"), shape = c(NA)))) +
  theme_minimal()+
  theme(legend.text = element_text(size = params$axis_size, family="Times"))
leg = get_legend(empty_plot)

plot_2x2 = plot_grid(plot_list[[1]], plot_list[[2]], plot_list[[3]], plot_list[[4]], nrow = 2)
plot_w_legend = plot_grid(plot_2x2, leg, ncol = 1, rel_heights = c(12, 1))
plot_w_legend

timestamp <- get_timestamp()
out_files <- c(glue(cl_args$OUT_DIR, "/time_varying_itt_plot_up_to_date.png"), 
               glue(cl_args$OUT_DIR, "/time_varying_itt_plot_{timestamp}.png"))
for (out_file in out_files) {
  ggsave(plot = plot_w_legend,
         filename = out_file,
         width = 10, height = 6, units = "in")
}

```

